package cn.edu.buaa.nlsde.grid.DatabaseManage;

import java.sql.*;

import cn.edu.buaa.nlsde.grid.DatabaseConnect.*;
import cn.edu.buaa.nlsde.grid.Structure.Host;

public class MetricSystemManage
{
	DBConn db=null;
	DBPool dbpool=null;
	Statement stat=null;
	
	public MetricSystemManage(DBConn db)
	{
		this.db=db;
	}
	public MetricSystemManage(DBPool db)
	{
		this.dbpool=db;
	}
	
	public ResultSet getData(int HostID)
	{
		String sql="select * from Metric_System where HostID="+HostID+" order by CollectTime desc LIMIT 1";
		//System.out.println(sql);
		try
		{
			stat=dbpool.connect();
			ResultSet rs=stat.executeQuery(sql);
			return rs;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}

	public ResultSet getData(int HostID,String start,String end)
	{
		String sql="select * from Metric_System where CollectTime>'"+start+"' and CollectTime<'"+end+"' and HostID="+HostID+" order by collectTime asc";
		System.out.println(sql);
		try
		{
			stat=dbpool.connect();
			ResultSet rs=stat.executeQuery(sql);
			return rs;
		}
		catch (Exception e)
		{
			e.printStackTrace();
			return null;
		}
	}
	
	public String addRecord(int HostID,Host host,String collectTime)
	{
		String machine_type=host.getMetric("machine_type");
		String boottime=host.getMetric("boottime");
		int cpu_num=Integer.parseInt(host.getMetric("cpu_num"));
		int cpu_speed=Integer.parseInt(host.getMetric("cpu_speed"));
		String os_name=host.getMetric("os_name");
		String os_release=host.getMetric("os_release");
		String gexec=host.getMetric("gexec");
		float part_max_used=Float.parseFloat(host.getMetric("part_max_used"));
		
		String sql="insert into Metric_System (HostID,machine_type,boottime,cpu_num,cpu_speed,os_name,os_release,gexec,part_max_used,CollectTime) values ("+HostID+",'"+machine_type+"','"+boottime+"',"+cpu_num+","+cpu_speed+",'"+os_name+"','"+os_release+"','"+gexec+"',"+part_max_used+",'"+collectTime+"')";
		System.out.println(sql);
		
		try
		{
			stat=dbpool.connect();
			stat.executeUpdate(sql);
			return "Success";
		} catch (Exception e)
		{
			return "Fail";
		}
	}

	public String deleteRecord(int HostID)
	{
		String sql="delete from Metric_System where HostID="+HostID;
		try
		{
			stat=dbpool.connect();
			stat.executeUpdate(sql);
			return "Success";
		}
		catch(Exception e)
		{
			return "Fail";
		}
	}
	
	public String deleteRecord(String start,String end)
	{
		String sql="delete from Metric_System where CollectTime>'"+start+"' and CollectTime<'"+end+"'";
		System.out.println(sql);
		try
		{
			stat=dbpool.connect();
			stat.executeUpdate(sql);
			return "Success";
		}
		catch(Exception e)
		{
			return "Fail";
		}
	}
	
	public void close() throws SQLException
	{
		dbpool.close();
	}
}
